const fs = require('fs')
const path = require('path')
const userSQL = require('../db/userSQL')
const goodsSQL = require('../db/goodsSQL')
const cartSQL=require('../db/cartSQL')
const {db,pool}=require('../db/db')

const getList = async (id, c, p) => {
  let result = await db(cartSQL.queryGoodsId, id)
  let result1=JSON.stringify(result)
  let result2=JSON.parse(result1)
  let goods=await db(goodsSQL.queryAll, [])
  let goods1=JSON.stringify(goods)
  let goods2=JSON.parse(goods1)
  let str=''
  result2.forEach(item=>{
    let goodsId=item.goods_id
    let is_select=item.is_select
    let goods3=goods2.find(item=>item.goods_id===goodsId)
    let val=JSON.stringify(goods3)
    str+=val.slice(0,-1)+',"is_select":'+is_select+'},'
  })
  let info1='['+str.slice(0,-1)+']'
  let info=JSON.parse(info1)
  return info
}
const getId = async (id,goodsId) => {
  let result = await db(cartSQL.queryAll, [])
  let data=result.filter(item => item.user_id === id)
  let data1=JSON.stringify(data)
  let info=JSON.parse(data1).filter(item => item.goods_id === goodsId)
  console.log(info)
  return info
}
const add = async (id, gId) => {
  let result = await db(userSQL.queryAll, [])
  pool.query(cartSQL.insert,[id,gId,0,1],(err,result)=>{undefined
    if(err) throw err;
    console.log(result);
  });
  return 'ok'
}

const select = async (id, gId) => {
  let result = await db(cartSQL.queryAll, [])
  let data=result.filter(item => item.user_id === id)
  let data1=JSON.stringify(data)
  let info=JSON.parse(data1).filter(item => item.goods_id === gId)
  let is_select= !info[0].is_select//修改goods中的is_select
  pool.query(cartSQL.updateCart,[Number(is_select),id,gId],(err,result)=>{undefined
    if(err) throw err;
    console.log(result);
  });

  return 'ok'
}


const remove = async (id, gId) => {
  await pool.query(cartSQL.deleteCart,[id,gId],(err,result)=>{undefined
    if(err) throw err;
    console.log(result);
  });
  return 'ok'
}

const selectAll = async (id, type) => {
  let result = await db(cartSQL.queryAll, [])
  let data=result.filter(item => item.user_id === id)
  let is_select= type ? true : false
  let data1=JSON.stringify(data)
  let data2=JSON.parse(data1)
  data2.forEach(item =>{
    pool.query(cartSQL.SelectAll,[Number(is_select),id],(err,result)=>{undefined
      if(err) throw err;
      console.log(result);
    });
  })
  return 'ok'
}

const removeSelect = async id => {
  let result = await db(cartSQL.queryAll, [])
  let data=result.filter(item => item.user_id === id)
  let data1=JSON.stringify(data)
  let data2=JSON.parse(data1).filter(item => item.is_select===1)
  data2.forEach(item=>{
    pool.query(cartSQL.deleteSelect,[id],(err,result)=>{undefined
      if(err) throw err;
      console.log(result);
    });
  })
  return 'ok'
}

module.exports = {
  getList,
  getId,
  add,
  select,
  remove,
  selectAll,
  removeSelect
}
